﻿module Sustainalytics.GCCS {

    import Common = Sustainalytics.Common;
    import Pager = Sustainalytics.Pager;

    export class GCMultiCompanyReportController {

        // order by
        public orderByCol: string;
        public orderByAsc: boolean;

        // list of multi company reports
        public companyReportList: GCOverallCompanySummaryExtendedDto[];
        public overallAssessments: { name: string; value: number; selected:boolean; disabled:boolean}[];
        public selectedAssessment: GCAssessment;
        public gcPermissions: GCCS.Security.GCPermissions;
        
        // total number of results
        public companyReportCount: number;

        private scopeDestroyed: boolean;


        // Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private $routeParams: ng.route.IRouteParamsService,
            private GCOverallCompanySummaryExtendedService: IGCOverallCompanySummaryExtendedService,
            private GCPermissionsService: GCCS.Security.IGCPermissionsService,
            private notificationFactory: Common.INotificationFactory,
            private staticObjects: Common.IStaticObjects) {

            var ctx = this;

            $scope['gcMultiCompanyReportCtrl'] = ctx;

            ctx.scopeDestroyed = false;
            ctx.selectedAssessment = null;
            ctx.gcPermissions = ctx.GCPermissionsService.getPermissions();
            /////////////////////////
            //ctx.gcPermissions.hasMultiCompWL = false;////////////////

            ctx.initOverallAssessments();

            ctx.orderByCol = "companyProfile.name";
            ctx.orderByAsc = true;
            ctx.handleScopeDestroyed();
            ctx.handlePagerChanged();
            
            
            //ctx.getCompanyReports(ctx.selectedAssessment);
        }

        private initOverallAssessments() {
            var ctx = this;

            // init the list of overall assessments
            ctx.overallAssessments =
            [
                { name: "Non-Compliant List", value: GCAssessment.NonCompliant, selected: false, disabled: false },
                { name: "WatchList", value: GCAssessment.Watchlist, selected: false, disabled: false },
                { name: "Non-Compliant List and WatchList", value: null, selected: true, disabled: false }
            ];


            // select default overall assessment
            if (ctx.gcPermissions.hasMultiCompNC && ctx.gcPermissions.hasMultiCompWL) {
                ctx.selectOverallAssessment(null);
            }
            else {
                if (ctx.gcPermissions.hasMultiCompNC) {
                    ctx.selectOverallAssessment(GCAssessment.NonCompliant);
                    ctx.overallAssessments[1].disabled = true;
                    ctx.overallAssessments[2].disabled = true;
                }
                if (ctx.gcPermissions.hasMultiCompWL) {
                    ctx.selectOverallAssessment(GCAssessment.Watchlist);
                    ctx.overallAssessments[0].disabled = true;
                    ctx.overallAssessments[2].disabled = true;
                }
            }


            // get overall assessment from URI
            var uriOverallAssessmentStr = ctx.$routeParams['overallAssessment'];
            uriOverallAssessmentStr = uriOverallAssessmentStr ? uriOverallAssessmentStr.toLowerCase() : null;

            // select overall assessment
            switch (uriOverallAssessmentStr) {
                case 'noncompliant':
                    if (!ctx.overallAssessments[GCAssessment.NonCompliant].disabled) {
                        ctx.selectOverallAssessment(GCAssessment.NonCompliant);
                    }
                    break;
                case 'watchlist':
                    if (!ctx.overallAssessments[GCAssessment.Watchlist].disabled) {
                        ctx.selectOverallAssessment(GCAssessment.Watchlist);
                    }
                    break;
            }
        }


        // when scope is destroyed keep a flag to prevent some operations
        // eg: bootstrap UI tab delete each tab and select the next that causing 
        // in current case to trigger multiple requests while tabs are being disposed 
        // which is unnecessary
        private handleScopeDestroyed() {
            var ctx = this;

            // when scope is destroyed
            ctx.$scope.$on('$destroy', function () {
                ctx.scopeDestroyed = true;
            });
        }


        private handlePagerChanged() {
            var ctx = this;

            ctx.$scope.$on('pagerChanged', function (ev, pager: Pager.PagerController) {
                ctx.getCompanyReports(ctx.selectedAssessment);
            });
        }

        private selectOverallAssessment(assessmentValue: GCAssessment) {
            var ctx = this;

            for (var i = 0; i < ctx.overallAssessments.length; i++) {
                ctx.overallAssessments[i].selected = false;
            }

            switch (assessmentValue) {
                case GCAssessment.NonCompliant:
                    ctx.selectedAssessment = GCAssessment.NonCompliant;
                    ctx.overallAssessments[0].selected = true;
                    break;
                case GCAssessment.Watchlist:
                    ctx.selectedAssessment = GCAssessment.Watchlist;
                    ctx.overallAssessments[1].selected = true;
                    break;
                case null:
                    ctx.selectedAssessment = null;
                    ctx.overallAssessments[2].selected = true;
                    break;
                default:
                    ctx.selectedAssessment = null;
            }
        }

        private getReportByAssessment(assessmentValue: number) {
            var ctx = this;
            ctx.selectOverallAssessment(assessmentValue);
            ctx.getCompanyReports(ctx.selectedAssessment);
        }

        private redirectToCompanyPage(companyName: string, assesmentValue: number) {
            var ctx = this;
            var overallAssesment = GCCS.GCUtility.getGcAssessmentUrlName(assesmentValue);
            ctx.$location.path('/research/globalcompact/company/' + companyName + '/' + overallAssesment);
        }

        // order list of portfolios
        public setOrderByCol(col: string) {
            var ctx = this;

            if (ctx.orderByCol === col) {
                ctx.orderByAsc = !ctx.orderByAsc;
            }
            else {
                ctx.orderByCol = col;
                ctx.orderByAsc = true;
            }
            ctx.getCompanyReports(ctx.selectedAssessment);
        }

        public getGCCSAssesmentByValue(val: number) {
            var ctx = this;
            return ctx.staticObjects.getGCCSAssesmentByValue(val);
        }

        public assessementHasClaims(val: number) {
            var ctx = this;
            switch (val) {
            case 1:
                return ctx.gcPermissions.hasMultiCompNC;
                break;
            case 2:
                return ctx.gcPermissions.hasMultiCompWL;
                break;
            case null:
                return ctx.gcPermissions.hasMultiCompNC && ctx.gcPermissions.hasMultiCompWL;
                break;
            default:
                return false;
            }
        }

        public getCompanyReports(overallAssessment?: GCAssessment): ng.IPromise<Common.PagedList<GCOverallCompanySummaryExtendedDto>> {
            var ctx = this;

            ctx.$rootScope['loading'] = true;

            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager) {
                var def = ctx.$q.defer();
                def.reject();
                return def.promise;
            }

            var skip = pager.skipCount();
            var take = pager.takeCount();


            var pagedListPromise: ng.IPromise<Common.PagedList<GCOverallCompanySummaryExtendedDto>> =
                ctx.GCOverallCompanySummaryExtendedService.GetPagedLst(skip, take, [ctx.orderByCol], ctx.orderByAsc, overallAssessment);

            pagedListPromise
                .then(function (pagedList: Common.PagedList<GCOverallCompanySummaryExtendedDto>) {
                    ctx.companyReportList = pagedList.items;
                    ctx.companyReportCount = pagedList.totalItemsCount;
                    pager.setTotalItemsCount(pagedList.totalItemsCount);
                })
                ['finally'](function () {
                    ctx.$rootScope['loading'] = false;
                });

            return pagedListPromise;
        }
    }


    // register controller with GCCS module
    angular.module('Sustainalytics.GCCS').controller('GCMultiCompanyReportController', GCMultiCompanyReportController);
}